const Koa = require("koa")
const koaCors = require('@koa/cors')

const app = new Koa()
const bodyParser = require("koa-bodyparser")
const router = require('./routes')
//数据库
require('./config/db.config');

//获取post参数
app.use(bodyParser())
// 配置 CORS 跨域
app.use(koaCors({
  origin: '*'
}))

//token拦截
app.use(async (ctx, next) => {
  //排除login相关的路由和接口
  if (ctx.url.includes("login")) {
    await next()
    return
  }
  const token = ctx.headers["authorization"]?.split(" ")[1]
  // console.log(req.headers["authorization"])
  if (token) {
    const payload = JWT.verify(token)
    if (payload) {
      //重新计算token过期时间
      const newToken = JWT.generate({
        _id: payload._id,
        username: payload.username
      }, "10s")

      ctx.set("Authorization", newToken)
      await next()
    } else {
      ctx.status = 401
      ctx.body = { errCode: -1, errInfo: "token过期" }
    }
  } else {
    await next()
  }
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)
console.log("_--_--_--_--_--_服务器运行成功:http://localhost:3000 --_--_--_--_--_--");

